package common

import (
	"awesomeProject/goprpoject/test11/model"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwKey = []byte("a_secret_crect") // 密钥

type Claims struct { // token里面添加用户信息，验证token后可能会用到用户信息
	jwt.StandardClaims
	UserID uint
}

func ReleaseToken(user model.Users) (string, error) {
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserID: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			Issuer:    "oceanlearn.tech",
			Subject:   "use token",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwKey)
	if err != nil {
		return "", err

	}
	return tokenString, nil

}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	// token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
	// 	return jwKey, nil
	// })

	// return token, claims, err
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwKey, nil
	})
	return token, claims, err
}
